<template>
  <div class="employee-list-container">
    <!-- 搜索区域 -->
    <div class="filter-section">
      <el-form :model="filterForm" inline>
        <el-form-item label="员工ID">
          <el-input v-model.number="filterForm.eid"  placeholder="员工ID" clearable style="width: 80px" />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="filterForm.name"  placeholder="请输入姓名" clearable style="width: 90px"/>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="filterForm.status"  placeholder="请选择" clearable style="width: 90px">
            <el-option label="全部" :value="null" />
            <el-option label="离职" :value="0" />
            <el-option label="休假" :value="1" />
            <el-option label="在职" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="权限">
          <el-select v-model="filterForm.permission"  placeholder="请选择" clearable style="width: 90px">
            <el-option label="全部" :value="null" />
            <el-option label="普通" :value="0" />
            <el-option label="财务" :value="1" />
            <el-option label="高层" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="证件照">
          <el-select v-model="filterForm.hasImage"  placeholder="请选择" clearable style="width: 90px">
            <el-option label="全部" :value="null" />
            <el-option label="已录入" :value="true" />
            <el-option label="未录入" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleFilter" :icon="Search">搜索</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
 
    <!-- 员工列表 -->
    <div class="table-section">
      <el-table 
        :data="tableData"
        v-loading="loading"
        style="width: 100%"
        height="calc(100vh - 250px)"
        stripe
      >
        <el-table-column prop="eid" label="员工ID" width="100" align="center" />
        <el-table-column prop="name" label="姓名" width="120" />
        
        <el-table-column label="证件照" width="120" align="center">
          <template #default="{ row }">
            <el-button 
              v-if="row.image"  
              type="text" 
              size="small"
              @click="viewEmployeeImage(row.image)" 
            >
              查看 
            </el-button>
            <span v-else>-</span>
          </template>
        </el-table-column>
 
        <el-table-column label="状态" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)"  size="small">
              {{ getStatusText(row.status)  }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="权限" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="getPermissionType(row.permission)"  size="small">
              {{ getPermissionText(row.permission)  }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="hiredate" label="入职日期" width="180" align="center">
          <template #default="{ row }">
            {{ formatDate(row.hiredate)  }}
          </template>
        </el-table-column>
        
        <el-table-column prop="phone" label="联系电话" width="150" align="center">
          <template #default="{ row }">
            {{ row.phone  ? `${row.phone.substring(0,  3)}****${row.phone.substring(7)}`  : '-' }}
          </template>
        </el-table-column>
        
        <el-table-column prop="cardid" label="身份证号" width="180" align="center">
          <template #default="{ row }">
            {{ row.cardid  ? `${row.cardid.substring(0,  6)}****${row.cardid.substring(14)}`  : '-' }}
          </template>
        </el-table-column>
        
        <el-table-column prop="address" label="地址" width="250" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.address  || '-' }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="180" fixed="right" align="center">
          <template #default="{ row }">
            <el-button size="small" type="primary" @click="showPermissionDialog(row)">
              设置职位 
            </el-button>
            <el-button size="small" type="success" @click="handleContact(row)">
              联系 
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
 
    <!-- 分页控制 -->
    <div class="pagination-section">
      <el-button 
        :disabled="!hasPrevPage || loading" 
        @click="loadPrevPage"
        v-if="hasPrevPage"
      >
        ← 上一页 
      </el-button>
      
      <el-button 
        :disabled="!hasNextPage || loading" 
        @click="loadNextPage"
        :loading="loading"
      >
        {{ loading ? '加载中...' : '下一页 →' }}
      </el-button>
 
      <span class="page-info" v-if="tableData.length  > 0">
        当前显示 {{ tableData.length  }} 条记录 
        <span v-if="!hasNextPage">- 已加载全部</span>
      </span>
    </div>



 
    <!-- 权限设置对话框 -->
    <el-dialog 
      v-model="permissionDialog.visible"  
      :title="`设置 ${permissionDialog.currentEmployee?.name}  的权限`"
      width="30%"
    >
      <el-select 
        v-model="permissionDialog.selectedPermission"  
        placeholder="请选择权限级别" 
        style="width: 100%"
      >
        <el-option :value="0" label="普通权限" />
        <el-option :value="1" label="财务权限" />
        <el-option :value="2" label="高层权限" />
      </el-select>
      <template #footer>
        <el-button @click="permissionDialog.visible  = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="confirmSetPermission"
          :loading="permissionDialog.loading" 
        >
          确认 
        </el-button>
      </template>
    </el-dialog>
 
    <!-- 证件照预览对话框 -->
    <el-dialog
      v-model="imagePreviewVisible"
      title="证件照预览"
      width="60%"
    >
      <div style="text-align: center;">
        <img :src="currentImage" style="max-width: 100%; max-height: 500px;" />
      </div>
    </el-dialog>
  </div>
</template>
 
<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Search, Picture } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { employee_listWithFiltersAPI, employee_setPermissionAPI } from '@/api/api'
import authStore from "@/model/authstore"
import { useRouter } from 'vue-router'
import dayjs from 'dayjs'
 
const router = useRouter()
 
// 图片预览 
const imagePreviewVisible = ref(false)
const currentImage = ref('')
 
// 过滤表单 
const filterForm = reactive({
  eid: null,
  name: '',
  status: null,
  permission: null,
  hasImage: null,
})
 
// 响应式数据
const loading = ref(false)
const tableData = ref([])
const nextCursor = ref(null)
const cursorStack = ref([])
const hasNextPage = ref(true)
const hasPrevPage = ref(false)
 
// 权限对话框数据 
const permissionDialog = reactive({
  visible: false,
  loading: false,
  currentEmployee: null,
  selectedPermission: 0
})
 
// 权限检查
const hasPermission = (requiredLevel) => {
  const user = authStore.get('auth')?.user  || {}
  return user.permission  >= requiredLevel 
}
 
// 状态和权限的显示文本 
const getStatusText = (status) => {
  const statusMap = { 0: '离职', 1: '休假', 2: '在职' }
  return statusMap[status] || '未知'
}
 
const getStatusType = (status) => {
  const typeMap = { 0: '', 1: 'warning', 2: 'success' }
  return typeMap[status] || 'info'
}
 
const getPermissionText = (permission) => {
  const permissionMap = { 0: '员工', 1: '财务', 2: '高层' }
  return permissionMap[permission] || '未知'
}
 
const getPermissionType = (permission) => {
  const typeMap = { 0: 'primary', 1: 'warning', 2: 'danger' }
  return typeMap[permission] || 'info'
}
 
// 构建请求参数（使用params对象）
const buildParams = (cursor = null) => {
  return {
    cursor: cursor,
    limit: 10,
    eid: filterForm.eid, 
    name: filterForm.name, 
    hiredate: null, // 保持与原来一致
    status: filterForm.status, 
    hasImage: filterForm.hasImage, 
    permission: filterForm.permission 
  }
}
 
// 处理分页响应
const handlePageResponse = (data) => {
  tableData.value  = data.data 
  nextCursor.value  = data.nextCursor  
  hasNextPage.value  = data.hasNext 
  hasPrevPage.value  = cursorStack.value.length  > 0
}
 
// 加载数据（带过滤条件）
const loadData = async (cursor = null) => {
  loading.value  = true
  try {
    const params = buildParams(cursor)
    const response = await employee_listWithFiltersAPI(params)
 
    if (response.code  === 200) {
      handlePageResponse(response.data) 
      ElMessage.success(' 数据加载成功')
    }
  } catch (error) {
    ElMessage.error(' 数据加载失败：' + error.message) 
  } finally {
    loading.value  = false 
  }
}
 
// 加载第一页
const loadFirstPage = async () => {
  cursorStack.value  = []
  await loadData(null)
}
 
// 加载下一页 
const loadNextPage = async () => {
  if (!nextCursor.value  || loading.value)  return
  
  loading.value  = true
  try {
    if (nextCursor.value)  {
      cursorStack.value.push(nextCursor.value) 
    }
 
    const params = buildParams(nextCursor.value) 
    const response = await employee_listWithFiltersAPI(params)
 
    if (response.code  === 200) {
      handlePageResponse(response.data) 
      ElMessage.success(' 下一页数据加载成功')
    }
  } catch (error) {
    ElMessage.error(' 加载下一页失败：' + error.message) 
  } finally {
    loading.value  = false
  }
}
 
// 加载上一页 
const loadPrevPage = async () => {
  if (cursorStack.value.length  <= 1) {
    await loadFirstPage()
    return 
  }
 
  loading.value  = true 
  try {
    cursorStack.value.pop() 
    const prevCursor = cursorStack.value[cursorStack.value.length  - 1] || null
 
    const params = buildParams(prevCursor)
    const response = await employee_listWithFiltersAPI(params)
 
    if (response.code  === 200) {
      handlePageResponse(response.data) 
      ElMessage.success(' 上一页数据加载成功')
    }
  } catch (error) {
    ElMessage.error(' 加载上一页失败：' + error.message) 
  } finally {
    loading.value  = false 
  }
}
 
// 过滤搜索 
const handleFilter = async () => {
  await loadFirstPage()
}
 
// 重置过滤 
const resetFilter = () => {
  filterForm.eid  = null
  filterForm.name  = ''
  filterForm.status  = null 
  filterForm.permission  = null 
  filterForm.hasImage  = null 
  loadFirstPage()
}
 
// 查看员工证件照
const viewEmployeeImage = (imageUrl) => {
  currentImage.value  = imageUrl 
  imagePreviewVisible.value  = true 
}
 
// 显示权限设置对话框 
const showPermissionDialog = (employee) => {
  permissionDialog.currentEmployee  = employee 
  permissionDialog.selectedPermission  = employee.permission  
  permissionDialog.visible  = true 
}
 
// 确认设置权限
const confirmSetPermission = async () => {
  if (!permissionDialog.currentEmployee)  return
 
  permissionDialog.loading  = true
  try {
    const response = await employee_setPermissionAPI({
      eid: permissionDialog.currentEmployee.eid, 
      permission: permissionDialog.selectedPermission 
    })
 
    if (response.code  === 200) {
      // 更新本地数据 
      permissionDialog.currentEmployee.permission  = permissionDialog.selectedPermission 
      ElMessage.success(` 已将 ${permissionDialog.currentEmployee.name}  的权限设置为 ${
        permissionDialog.selectedPermission  === 0 ? '普通权限' :
        permissionDialog.selectedPermission  === 1 ? '财务权限' : '高层权限'
      }`)
      permissionDialog.visible  = false
    } else {
      ElMessage.error(response.message  || '权限设置失败')
    }
  } catch (error) {
    ElMessage.error(` 设置权限失败: ${error.message}`) 
    console.error(' 设置权限错误:', error)
  } finally {
    permissionDialog.loading  = false 
  }
}
 
// 联系员工 
const handleContact = (row) => {
  ElMessage.success(` 正在联系员工 ${row.name}  (电话: ${row.phone})`) 
  // 这里可以添加联系员工的逻辑 
}
 
// 日期格式化 
const formatDate = (dateString) => {
  if (!dateString) return '-'
  return dayjs(dateString).format('YYYY-MM-DD')
}
 
// 初始化加载 
onMounted(() => {
  loadFirstPage()
})
</script>
 
<style scoped>
.employee-list-container {
  padding: 20px;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f7fa;
}
 
.filter-section {
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
 
.table-section {
  flex: 1;
  margin-bottom: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}
 
.pagination-section {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 15px 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
 
.page-info {
  color: #606266;
  font-size: 14px;
  margin-left: auto;
}
 
.el-tag {
  margin: 2px;
}
 
.el-form-item {
  margin-bottom: 0;
  margin-right: 10px;
}
 
.el-button--text {
  padding: 0;
}
</style> 